package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.AgeCalculator;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author guo
 * @date 2024-11-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getDetailById(Integer id) {
        //1.查询入住信息 checkIn
        CheckIn checkIn = getById(id);


        //2.查询老人信息
        /*LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper();
        elderQueryWrapper.eq(Elder::getIdCardNo,checkIn.getIdCardNo());
        Elder elder = elderMapper.selectOne(elderQueryWrapper);*/
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBeanIgnoreError(elder, CheckInElderVo.class);

        //设置属性
        /*CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setId(checkIn.getId());
        checkInElderVo.setName(checkIn.getElderName());
        checkInElderVo.setIdCardNo(checkIn.getIdCardNo());

        checkInElderVo.setBirthday(elder.getBirthday());
        checkInElderVo.setSex(elder.getSex());
        checkInElderVo.setPhone(elder.getPhone());
        checkInElderVo.setAddress(elder.getAddress());
        checkInElderVo.setImage(elder.getImage());
        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
        checkInElderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());*/

        //计算老人的生日
        int age = AgeCalculator.calculateAgeFromIdCard(elder.getIdCardNo());
        //int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo()); 优先使用hutool的
        checkInElderVo.setAge(age);
        //3.查询合同
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
        //4.查询入住配置
        //checkIn

        LambdaQueryWrapper<CheckInConfig> checkInLambdaQuery = new LambdaQueryWrapper();
        checkInLambdaQuery.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInLambdaQuery);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBeanIgnoreError(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());

        //5.转换家属列表
        /*String json = checkIn.getRemark();

        ObjectMapper objectMapper = new ObjectMapper();

        List<ElderFamilyVo> elderFamilyVoList = null;
        try {
            elderFamilyVoList = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, ElderFamilyVo.class));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }*/

        //用alibaba的api
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);

        //6.整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo(checkInElderVo,elderFamilyVoList,checkInConfigVo,contract);
        return checkInDetailVo;
    }

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.判断老人是否入住
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());

        Elder elderIn = elderMapper.selectOne(lambdaQueryWrapper);
        if (elderIn != null && elderIn.getStatus() >= 1 && elderIn.getStatus() < 5) {
            throw new ServiceException("该老人已入住");
        }
        //2.更新床位状态为已入住
        //通过床位的id查询床位是否有人占用
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        if (bed.getBedStatus() == 1) {
            throw new ServiceException("该床位有人入住");
        }
        //更新床位的状态
        LambdaUpdateWrapper<Bed> bedLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        bedLambdaUpdateWrapper.set(Bed::getBedStatus,1);
        // 多线程下需加锁，利用的是数据库行锁，如果更新成功返回值为>=1, 否则返回值为0代表没有更新成功，说明被其他线程更新了该行数据
        //数据库行锁(乐观锁)
        bedLambdaUpdateWrapper.eq(Bed::getBedStatus,0);
        bedLambdaUpdateWrapper.eq(Bed::getId,bed.getId());
        //要更新的对象。如果为 null，则表示不更新任何字段。
        //更新的记录,返回手影响的行数
        int update = bedMapper.update(null, bedLambdaUpdateWrapper);
        if (update == 0) {
            throw new ServiceException("该床位有人入住");
        }

        //3.新增或更新老人
        Elder elder = insertOrUpdate(elderIn,bed,dto);
        //4.新增签约办理
        insertContract(elder,dto);
        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, bed, dto);
        //6.新增入住配置
        insertCheckInConfig(dto,checkIn.getId());
    }



    /**
     * 新增入住配置
     * @param dto
     * @param id
     */
    private void insertCheckInConfig(CheckInApplyDto dto, Long id) {
        CheckInConfig config = BeanUtil.toBeanIgnoreError(dto.getCheckInConfigDto(), CheckInConfig.class);
        config.setCheckInId(id);
        checkInConfigMapper.insertCheckInConfig(config);

    }

    /**
     * 新增入住信息
     * @param elder
     * @param bed
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder, Bed bed, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        //设置老人的家属信息
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0); //已入住
        save(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param elder
     * @param dto
     */
    private void insertContract(Elder elder, CheckInApplyDto dto) {
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        Contract contract = BeanUtil.toBeanIgnoreError(dto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStatus(0);//未生效, 后期审核与支付后才会生效
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contractMapper.insertContract(contract);
    }

    /**
     * 新增或更新老人
     * @param elderIn
     * @param bed
     * @param dto
     * @return
     */
    private Elder insertOrUpdate(Elder elderIn, Bed bed, CheckInApplyDto dto) {
        //创建并拷贝对象属性值,忽略错误的
        //类型转换
        Elder elder = BeanUtil.toBeanIgnoreError(dto.getCheckInElderDto(),Elder.class);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        if (null != elderIn) {
            //修改
            elder.setId(elderIn.getId());
            elderMapper.updateById(elder);
        }else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}
